<template>
  <div>
    <MyHeader title="购物车案例"></MyHeader>
    <div class="main">
      <MyGoods
        v-for="item in goodList"
        :key="item.id"
        :id="item.id"
        :name="item.goods_name"
        :img="item.goods_img"
        :price="item.goods_price"
        :count="item.goods_count"
        :state="item.goods_state"
        @changeState="changeState"
        @minus="minus"
        @plus="plus"
      ></MyGoods>
    </div>
    <MyFooter
      :total="total()"
      :length="length"
      :all="selectAll"
      @changeAll="changeAll"
    ></MyFooter>
  </div>
</template>

<script>
import MyHeader from './components/MyHeader'
import MyGoods from './components/MyGoods'
import MyFooter from './components/MyFooter'
import axios from 'axios'
export default {
  components: {
    MyHeader,
    MyGoods,
    MyFooter,
  },
  async created() {
    const {
      data: { list },
    } = await axios.get('https://www.escook.cn/api/cart')
    this.goodList = list
  },
  methods: {
    total() {
      const arr = this.goodList.filter((item) => item.goods_state)
      this.length = arr.length
      return arr.reduce(
        (sum, item) => sum + item.goods_count * item.goods_price,
        0
      )
    },
    changeState(id){
      const obj = this.goodList.find(item => item.id == id)
      obj.goods_state = !obj.goods_state
    },
    minus(id,num){
      const obj = this.goodList.find(item => item.id == id)
      obj.goods_count = num
    },
    plus(id,num){
      const obj = this.goodList.find(item => item.id == id)
      obj.goods_count = num
    },
    changeAll(val){
      this.goodList.forEach(item => item.goods_state = val)
    }
  },
  computed:{
    selectAll(){
     return  this.goodList.every(item => item.goods_state)
    }
  },
  data() {
    return {
      goodList: [],
      length:0,
    }
  },
}
</script>

<style>
.main {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
